<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航 -->

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索和添加用户 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input placeholder="请输入内容" v-model="queryData.query" class="input-with-select" @clear="getUserList" clearable>
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
             <el-button type="primary" @click="addUserFlag = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 添加用户弹出框 -->
        <el-dialog
          @close="dialogClose"
          title="添加用户"
          :visible.sync="addUserFlag"
          width="50%">
          <el-form ref="addUserForm" :model="addUserForm" label-width="80px" :rules="addUserRules">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addUserFlag = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 表格 -->
        <el-table :data="users" style="width: 100%" stripe border>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="username" label="用户名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userChange(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button @click="editUser(scope.row)" size="mini" type="primary" icon="el-icon-edit"></el-button>
              <el-button @click="delUser(scope.row)" size="mini" type="danger" icon="el-icon-delete"></el-button>
               <el-tooltip effect="dark" content="用户设置" placement="top" :enterable="false">
                  <el-button @click="settingUser(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
                </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分配角色对话框 -->
        <el-dialog
          @close="roleNum = ''"
          title="提示"
          :visible.sync="setDialogFlag"
          width="50%">
          <div>
            <p>用户的姓名：{{userInfo.username}} </p><br>
            <p>用户当前角色：{{userInfo.role_name}} </p><br>
            <p>分配新角色：
              <!-- 下拉选择框 -->
              <el-select v-model="roleNum" placeholder="请选择">
                <el-option
                  v-for="item in roles"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
                </el-option>
              </el-select></p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setDialogFlag = false">取 消</el-button>
            <el-button type="primary" @click="setRole">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 修改用户信息对话框 -->
        <el-dialog
          @close="editdialogClose"
          title="修改用户信息"
          :visible.sync="editUserFlag"
          width="30%">
          <el-form ref="editForm" :model="userInfo" :rules="addUserRules" label-width="80px">
            <el-form-item label="用户名">
              <el-input disabled v-model="userInfo.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="userInfo.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editUserFlag = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分页功能 -->
         <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryData.pagenum"
          :page-sizes="[1, 2, 4, 8]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
    <!-- 卡片视图 -->
  </div>
</template>

<script>
export default {
  data () {
    // 用户名验证规则
    const checkName = (emm, value, callback) => {
      const reg = /^[a-zA-Z0-9_-]*$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('用户名格式不正确'))
    }
    // 邮箱验证规则
    const checkEmail = (emm, value, callback) => {
      const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('邮箱格式不正确'))
    }
    // 手机号码验证规则
    const checkMobile = (emm, value, callback) => {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return callback()
      }
      callback(new Error('手机号码格式不正确'))
    }
    return {
      queryData: {
        query: '',
        // 请求第几页数据
        pagenum: 1,
        // 每页几条数据
        pagesize: 2
      },
      users: [],
      total: 0,
      // 控制添加用户弹出框是否显示，false不显示
      addUserFlag: false,
      // 添加用户表单数据
      addUserForm: {
        username: 'binary',
        password: '123456789',
        email: '7392@qq.com',
        mobile: '17630023000'
      },
      // 校验规则
      addUserRules: {
        username: [
          { validator: checkName, trigger: 'blur' },
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUserFlag: false,
      // 修改用户时的数据
      userInfo: {},
      // 控制分配角色对话框显示与否
      setDialogFlag: false,
      // 角色数据
      roles: [],
      roleNum: ''
    }
  },

  created () {
    this.getUserList()
  },

  methods: {
    // 数据初始化
    async getUserList () {
      const { data: res } = await this.$axios.get('users', { params: this.queryData })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      this.users = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 每页几条数据发生变化时重新加载
    handleSizeChange (newSize) {
      this.queryData.pagesize = newSize
      this.getUserList()
    },
    // 查询第几页数据是重新加载
    handleCurrentChange (newNum) {
      this.queryData.pagenum = newNum
      this.getUserList()
    },
    // 更改开关状态时触发
    async userChange (val) {
      const { id, mg_state: state } = val
      const { data: res } = await this.$axios.put(`users/${id}/state/${state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error('更改状态失败')
      }
      return this.$message.success('更改状态成功')
    },
    // 添加用户对话框关闭时触发
    dialogClose () {
      this.$refs.addUserForm.resetFields()
    },
    // 添加用户功能
    addUser () {
      this.$refs.addUserForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addUserFlag = false
        this.getUserList()
      })
    },
    // 修改用户信息处理函数
    editUser (value) {
      this.editUserFlag = true
      console.log(value)
      this.userInfo = JSON.parse(JSON.stringify(value))
    },
    // 修改用户信息确定处理
    editUserInfo () {
      this.$refs.editForm.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`users/${this.userInfo.id}`, this.userInfo)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editUserFlag = false
        this.getUserList()
      })
    },
    // 修改用户信息弹出框关闭时重置回原来状态
    editdialogClose () {
      this.$refs.editForm.resetFields()
    },
    // 删除用户操作
    delUser (val) {
      this.$confirm('是否删除该用户数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`users/${val.id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getUserList()
        return this.$message.success('删除成功!')
      }).catch(() => {
        return this.$message('已取消删除')
      })
    },
    // 设置用户操作
    async settingUser (row) {
      this.userInfo = row
      this.setDialogFlag = true
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roles = res.data
    },
    // 发起请求分配角色
    async setRole () {
      if (!this.roleNum) return this.$message.error('请选择要分配的角色')
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.roleNum })
      if (res.meta.status !== 200) return this.$message.error('设置角色失败')
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setDialogFlag = false
    }
  }
}
</script>

<style scoped lang='less'>
</style>
